﻿using Interfaces.Library;
using Interfaces.Model;
using Models;
using Newtonsoft.Json;
using NLog;
using System.Globalization;
using Microsoft.Extensions.DependencyInjection;
using Respository;

namespace Services
{
    /// <summary>
    /// 数据采集的工具类
    /// </summary>
    public class WorkPieceDataCaptureHelper : IWorkPieceDataCaptureLibrary
    {
        private IServiceProvider _serviceProvider;
        private MQTT_Client mqtt;
        private TcpDataListener? tcpDataListener;  // TCP监听器
        Logger log = LogManager.GetCurrentClassLogger();
        WorkPieceDataCaptureRespository? respository;    //数据库操作类
        EmployeeAttendanceRepository? employeeAttendanceRepository;  //员工考勤数据库操作类
        List<tb_WorkPieceDataCapture_Realtime>? cache_DataCapture;  //待保存数据的缓存
        List<tb_PointCheckRecord>? cache_PointCheckDataCapture;  //待保存点检数据的缓存
        Thread? thread_SaveData; //保存数据的线程
        bool switch_thread_SaveData = true; //保存数据的线程开关
        Thread? thread_SavePointCheckData; //保存点检数据的线程
        bool switch_thread_SavePointCheckData = true; //保存点检数据的线程开关
        Thread? thread_CheckPLCState;    //检测PLC连接状态的线程
        bool switch_thread_CheckPLCState = true;    //检测PLC连接状态的线程开关
        plcConnectionState? plcState;    //plc的连接状态
        public delegate void feedbackNewestSavedData(tb_WorkPieceDataCapture_Realtime model);    //向调用者反馈最新采集到的数据的代理方法
        public event feedbackNewestSavedData? evt_FeedingNewestData; //向调用者反馈最新采集的数据的事件
        public delegate void feedbackNewestSummaryData(tb_WorkPieceDataCapture_Realtime model);    //向调用者反馈最新产量统计的代理方法
        public event feedbackNewestSummaryData? evt_FeedingNewestSummary; //向调用者反馈最新产量统计的事件
        public delegate void feedbackNewestPointCheckData(PointCheckRecord model);    //向调用者反馈最新点检数据的代理方法
        public event feedbackNewestPointCheckData? evt_FeedingNewestPointCheckData; //向调用者反馈最新点检数据的事件

        public delegate void feedbackPLCConnectionState(plcConnectionState model); //向调用者反馈PLC连接状态的代理方法
        public event feedbackPLCConnectionState? evt_FeedingState; //向调用者反馈PLC连接状态的事件
        private string strLastSerialNo = "";    //记录一下上一次保存的数据序列号
        /// <summary>
        /// 构造函数
        /// </summary>
        public WorkPieceDataCaptureHelper(IServiceProvider serviceProvider, MQTT_Client mqttClient)
        {
            this._serviceProvider = serviceProvider;
            this.mqtt = mqttClient;

            // 获取TCP监听器实例
            this.tcpDataListener = serviceProvider.GetService<TcpDataListener>();

            // 初始化员工考勤数据库操作类
            this.employeeAttendanceRepository = new EmployeeAttendanceRepository(serviceProvider);

            this.initialize();
        }
        ~WorkPieceDataCaptureHelper()
        {
            this.switch_thread_CheckPLCState = false;
            this.switch_thread_SaveData = false;
            this.switch_thread_SavePointCheckData = false;

            // 停止TCP监听器
            this.tcpDataListener?.Stop();
        }
        /// <summary>
        /// 界面初始化
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IFuncResult<string> initialize()
        {
            var result = new FuncResult<string>();
            try
            {
                this.respository = new WorkPieceDataCaptureRespository(this._serviceProvider);
                //初始化数据缓存容器
                cache_DataCapture = new List<tb_WorkPieceDataCapture_Realtime>();
                cache_PointCheckDataCapture = new List<tb_PointCheckRecord>();
                //绑定MQTT事件
                this.mqtt.onMQTTMessageReceived += this.MQTT_MessageReceived;
                //启动读数据的线程
                this.thread_CheckPLCState = new Thread(this.doCheckMQTTState);
                this.thread_CheckPLCState.IsBackground = true;
                this.thread_CheckPLCState.Start();
                //启动保存数据的线程
                this.thread_SaveData = new Thread(this.doSaveData);
                this.thread_SaveData.IsBackground = true;
                this.thread_SaveData.Start();
                //启动保存点检数据的线程
                this.thread_SavePointCheckData = new Thread(this.doSavePointCheckData);
                this.thread_SavePointCheckData.IsBackground = true;
                this.thread_SavePointCheckData.Start();

                // 启动TCP监听器
                if (this.tcpDataListener != null)
                {
                    this.tcpDataListener.EmployeeDataReceived += this.OnEmployeeDataReceived;
                    this.tcpDataListener.Start();
                    log.Info("TCP监听器已在WorkPieceDataCaptureHelper中启动");
                }

                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }


        //执行检测PLC当前连接状态
        public void doCheckMQTTState()
        {
            plcState = new plcConnectionState();
            while (switch_thread_CheckPLCState)
            {
                try
                {
                    plcState.connectionState = enum_PlcConnectionState.Connected;
                    Thread.Sleep(10000);
                }
                catch (Exception ex)
                {

                }
            }
        }

        public IFuncResult<string> doConnectPLC()
        {
            var result = new FuncResult<string>();
            try
            {
                result.bSuccess = true;
            }
            catch (Exception ex)
            {
                result.setException(ex);
            }
            return result;
        }
        /// <summary>
        /// 执行读数据
        /// </summary>
        public void doReadProduceData(string strSeed, IDataModel model_data)
        {
            try
            {
                var model = model_data as tb_WorkPieceDataCapture_Realtime;
                if (model == null)
                {
                    Random random = new Random();
                    // 定义两个小数
                    double minValue = 1.0;
                    double maxValue = 10000.0;
                    model = new tb_WorkPieceDataCapture_Realtime()
                    {
                        //总成
                        ZC_Result = (DateTime.Now.Second % 2 == 0 ? "OK" : "NG"),
                        ZC_LaserNo = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        ZC_SerialNo = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        ZC_Time = DateTime.Now.ToString("yyyyMMddHHmmss"),
                        ZC_ProduceMode = (DateTime.Now.Second % 4 + 1).ToString(), // 生成1-4的随机数值
                        ZC_Model = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        // 打码检测（新增）
                        ZC_DM_Result = (DateTime.Now.Millisecond % 2 == 0 ? "1" : "2"),
                        ZC_DM_ScanText = "LASER-" + random.Next(100000, 999999),
                        ZC_DM_Photo = "e:\\laser\\test.jpg",
                        //主体
                        FLJ_ZT_Material = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_ZT_Model = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        //一次圈
                        FLJ_YCQ_Result = "1",
                        FLJ_YCQ_Material = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_YCQ_Model = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_YCQ_Photo = "e:\\aaa.jpg",
                        //隔离环
                        FLJ_GLH_Result = "1",
                        FLJ_GLH_Material = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_GLH_Model = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_GLH_Photo = "e:\\aaa.jpg",
                        //二次圈
                        FLJ_ECQ_Result = "1",
                        FLJ_ECQ_Material = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_ECQ_Model = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_ECQ_Photo = "e:\\aaa.jpg",
                        //安全环
                        FLJ_KZH_Result = "OK",
                        FLJ_KZH_Value = (random.NextDouble() * (maxValue - minValue) + minValue),
                        FLJ_KZH_Material = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_KZH_Model = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_KZH_Lower = (random.NextDouble() * (maxValue - minValue) + minValue),
                        FLJ_KZH_Upper = (random.NextDouble() * (maxValue - minValue) + minValue),
                        FLJ_KZH_PressureResult = (DateTime.Now.Millisecond % 3 == 0 ? "1" : (DateTime.Now.Millisecond % 3 == 1 ? "2" : "0")),
                        //锁扣
                        FLJ_SK_Result = "1",
                        FLJ_SK_Material = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_SK_Model = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_SK_Photo = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        //内密气密
                        JCY_QM_Program = 12,
                        JCY_QM_Result = "1",
                        JCY_QM_Leak = (random.NextDouble() * (maxValue - minValue) + minValue),
                        JCY_QM_Pressure = (random.NextDouble() * (maxValue - minValue) + minValue),
                        //外密
                        FLJ_WM_Result = "1",
                        FLJ_WM_Photo1 = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_WM_Photo2 = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_WM_Material = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        FLJ_WM_Model = "1",
                        //壳体气密
                        JCY_KTQM_Program = 1,
                        JCY_KTQM_Result = "1",
                        JCY_KTQM_Leak = (random.NextDouble() * (maxValue - minValue) + minValue),
                        JCY_KTQM_Pressure = (random.NextDouble() * (maxValue - minValue) + minValue),
                        //上料
                        FLJ_SL_Photo = "e:\\aaa.jpg",
                        FLJ_SL_Photo2 = "e:\\aaa2.jpg",
                        //内密
                        FLJ_NM_Photo = "e:\\nm_test.jpg",
                        FLJ_NM_Result = (DateTime.Now.Second % 2 == 0 ? "1" : "2"),
                        //登录人员
                        LoginUser = "测试用户" + random.Next(1, 10),
                        dDate = DateTime.Now
                    };
                    model.FLJ_ECQ_Result = "1";
                    model.FLJ_GLH_Result = "1";
                    model.FLJ_KZH_Result = model.FLJ_KZH_Value > 9800 ? "2" : "1";
                    model.FLJ_SK_Result = double.Parse(model.FLJ_SK_Model) > 9800 ? "2" : "1";
                    model.JCY_QM_Result = model.JCY_QM_Leak > 9800 ? "2" : "1";
                    model.JCY_KTQM_Result = "1";
                    model.FLJ_WM_Result = double.Parse(model.FLJ_WM_Photo1) > 9800 ? "2" : "1";
                    model.FLJ_YCQ_Result = "1";
                    model.ZC_Result = model.FLJ_ECQ_Result == "1" &&
                                                 model.FLJ_GLH_Result == "1" &&
                                                 model.FLJ_KZH_Result == "1" &&
                                                 model.FLJ_SK_Result == "1" &&
                                                 model.JCY_QM_Result == "1" &&
                                                 model.FLJ_ECQ_Result == "1" &&
                                                 model.FLJ_WM_Result == "1" &&
                                                 model.FLJ_YCQ_Result == "1" ? "1" : "2";
                }
                #region 对OK和NG的特殊处理
                model.ZC_Result = WorkPieceDataService.transformTestValue(model.ZC_Result);   //总成
                model.FLJ_YCQ_Result = WorkPieceDataService.transformTestValue(model.FLJ_YCQ_Result);   //一次圈
                model.FLJ_GLH_Result = WorkPieceDataService.transformTestValue(model.FLJ_GLH_Result);  //隔离环
                model.FLJ_ECQ_Result = WorkPieceDataService.transformTestValue(model.FLJ_ECQ_Result);   //二次圈
                model.FLJ_KZH_Result = WorkPieceDataService.transformTestValue(model.FLJ_KZH_Result);   //安全环
                model.FLJ_SK_Result = WorkPieceDataService.transformTestValue(model.FLJ_SK_Result);   //锁扣
                model.JCY_KTQM_Result = WorkPieceDataService.transformTestValue(model.JCY_KTQM_Result);    //壳体气密
                model.FLJ_WM_Result = WorkPieceDataService.transformTestValue(model.FLJ_WM_Result);   //外密
                // 新增字段转换
                model.FLJ_NM_Result = WorkPieceDataService.transformTestValue(model.FLJ_NM_Result);     // 内密检测结果
                model.FLJ_KZH_PressureResult = WorkPieceDataService.transformTestValue(model.FLJ_KZH_PressureResult); // 安全环压力检测结果
                model.JCY_QM_Result = WorkPieceDataService.transformTestValue(model.JCY_QM_Result);    //内密气密
                model.ZC_DM_Result = WorkPieceDataService.transformTestValue(model.ZC_DM_Result);      //打码检测结果
                // 生产模式转换
                model.ZC_ProduceMode = WorkPieceDataService.transformProduceModeValue(model.ZC_ProduceMode);
                model.dDate = DateTime.Now;
                #endregion
                lock (this.cache_DataCapture)
                {
                    this.cache_DataCapture.Add(model);
                    log.Info("(" + strSeed + ")成功将实体类加入待存储缓存");
                }
            }
            catch (Exception ex)
            {
                log.Error("(" + strSeed + ")将实体类加入待存储缓存出错！" + ex.ToString());
            }
        }
        /// <summary>
        /// 执行保存数据
        /// </summary>
        public void doSaveData()
        {
            while (switch_thread_SaveData)
            {
                try
                {
                    if (this.cache_DataCapture != null && this.cache_DataCapture.Count > 0)
                    {
                        var model = this.cache_DataCapture[0];
                        var result = this.respository.saveData(model);
                        bool dataSaved = false;
                        MQTT_Message msg = new MQTT_Message();
                        msg.Topic = "BM21生产数据存储结果";
                        if (result.bSuccess)    //成功写入了数据库
                        {
                            log.Info("(model.ZC_SerialNo为" + model.ZC_SerialNo + ")的数据存储成功");
                            msg.text = "{\"ZC_SerialNo\":\"" + model.ZC_SerialNo + "\",\"result\":1,\"msg\":\"\"}";
                            dataSaved = true;
                        }
                        else    //写入数据库失败时往文件里写
                        {
                            try
                            {
                                string strDataJson = JsonConvert.SerializeObject(model);
                                File.AppendAllLines("Files\\UnsavedData", new List<string>() { strDataJson });
                                log.Error("(model.iID为" + model.ZC_SerialNo + ")的数据存储到数据库失败，已写入文件中待人工处理");
                                msg.text = "{\"ZC_SerialNo\":\"" + model.ZC_SerialNo + "\",\"result\":1,\"msg\":\"数据存储到数据库失败(" + result.strMsg + ")，已写入文件中待人工处理\"}";
                                dataSaved = true;
                            }
                            catch (Exception ex)
                            {
                                log.Error("(model.ZC_SerialNo为" + model.ZC_SerialNo + ")的数据写入文件中待人工处理失败，需根据iID排查日志中的源报文进行处置");
                                msg.text = "{\"ZC_SerialNo\":\"" + model.ZC_SerialNo + "\",\"result\":0,\"msg\":\"数据存储到数据库与文件均失败\"}";
                                dataSaved = false;
                            }
                        }
                        this.MQTTPublish(msg);
                        this.cache_DataCapture.RemoveAt(0);

                        if (this.evt_FeedingNewestData != null && dataSaved) this.evt_FeedingNewestData(model);  //向调用者反馈最新的生产数据
                    }
                    Thread.Sleep(300);
                }
                catch (Exception ex)
                {
                    log.Error("存储数据出现未捕获的异常！" + ex.ToString());
                }
            }
        }

        private void MQTT_MessageReceived(MQTT_Message msg)
        {
            switch (msg.Topic)
            {
                case "BM21生产数据":
                    if (msg.text == "测试用例")
                    {
                        this.doReadProduceData(Guid.NewGuid().ToString(), null);
                        return;
                    }
                    tb_WorkPieceDataCapture_Request? request;
                    tb_WorkPieceDataCapture_Realtime model;
                    MQTT_Message msg_feedback = new MQTT_Message();
                    msg_feedback.Topic = "BM21生产数据存储结果";
                    string strSeed = Guid.NewGuid().ToString();
                    try
                    {
                        log.Info("(" + strSeed + ")接收到生产数据:" + msg.text);
                        #region 对信息的特殊处理
                        msg.text = msg.text.Replace("\\u0000", "");
                        #endregion
                        request = JsonConvert.DeserializeObject<tb_WorkPieceDataCapture_Request>(msg.text);
                        if (request != null)
                        {
                            DateTime dateTime = DateTime.Now;
                            if (string.IsNullOrEmpty(request.ZC_SerialNo))
                            {
                                log.Error("(" + strSeed + ")解析成实体类出错,总成序列号为空");
                                msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"解析成实体类出错,总成序列号为空\"}";
                                this.MQTTPublish(msg_feedback);
                            }
                            //else if (!DateTime.TryParseExact(request.ZC_Time, "yyyyMMddHHmmss", new CultureInfo("en-US"), DateTimeStyles.None, out dateTime))
                            //{
                            //    log.Error("(" + strSeed + ")解析成实体类出错,无法将ZC_Time的值" + request.ZC_Time + "转换成日期时间");
                            //    msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":\"0\",\"msg\":\"解析成实体类出错,无法将ZC_Time的值" + request.ZC_Time + "转换成日期时间\"}";
                            //    this.MQTTPublish(msg_feedback);
                            //}
                            else
                            {
                                #region 对数据进行过滤或保存
                                //设备无法通过信号控制网关传数据，只能每秒发一次，通过判断新接到的数据的总成序列号与上次的不一致则认定为新数据
                                if (request.ZC_SerialNo == strLastSerialNo)
                                {
                                    log.Info("(" + strSeed + ")此为重复数据，不做任何处理");
                                    msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"此为重复数据，不做任何处理\"}";
                                    this.MQTTPublish(msg_feedback);
                                }
                                else
                                {
                                    strLastSerialNo = request.ZC_SerialNo;
                                    request.iID = null;
                                    request.dDate = dateTime;

                                    // 确保新字段有默认值（如果MQTT数据中没有这些字段）
                                    if (string.IsNullOrEmpty(request.FLJ_NM_Photo))
                                        request.FLJ_NM_Photo = "";
                                    if (string.IsNullOrEmpty(request.FLJ_NM_Result))
                                        request.FLJ_NM_Result = "";
                                    if (string.IsNullOrEmpty(request.LoginUser))
                                        request.LoginUser = "";
                                    if (string.IsNullOrEmpty(request.ZC_ProduceMode))
                                        request.ZC_ProduceMode = "";
                                    if (string.IsNullOrEmpty(request.FLJ_SL_Photo2))
                                        request.FLJ_SL_Photo2 = "";

                                    #region 总成标识码的校验
                                    if (string.IsNullOrEmpty(request.ZC_SerialNo))    //总成标识码任何时候不能为空
                                    {
                                        log.Error("(" + strSeed + ")总成序列号不能为空");
                                        msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"总成序列号不能为空\"}";
                                        this.MQTTPublish(msg_feedback);
                                        return;
                                    }
                                    var result_SerialNo = respository.getBySerialNoFromRealTime(request.ZC_SerialNo); //总成标识码不能重复
                                    if (result_SerialNo.bSuccess)
                                    {
                                        if (result_SerialNo.obj_Return != null)
                                        {
                                            log.Info("(" + strSeed + ")在库中找到相同的总成标识码，此为重复数据，不做任何处理");
                                            msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"在库中找到相同的总成标识码，此为重复数据，不做任何处理\"}";
                                            this.MQTTPublish(msg_feedback);
                                            return;
                                        }
                                    }
                                    else
                                    {
                                        log.Info("(" + strSeed + ")校验数据是否重复出错!" + result_SerialNo.strMsg);
                                        msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"校验数据是否重复出错!" + result_SerialNo.strMsg + "\"}";
                                        this.MQTTPublish(msg_feedback);
                                        return;
                                    }
                                    #endregion
                                    #region 激光打标码的校验
                                    if (request.CheckLaserNo == true)
                                    {
                                        if (string.IsNullOrEmpty(request.ZC_LaserNo))     //总成激光码不能为空
                                        {
                                            log.Error("(" + strSeed + ")总成激光码不能为空");
                                            msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"总成激光码不能为空\"}";
                                            this.MQTTPublish(msg_feedback);
                                            return;
                                        }
                                        var result_LaserNo = respository.getByLaserNoFromRealTime(request.ZC_LaserNo); //激光码不能重复
                                        if (result_LaserNo.bSuccess)
                                        {
                                            if (result_LaserNo.obj_Return != null)
                                            {
                                                log.Info("(" + strSeed + ")在库中找到相同的激光码，此为重复数据，不做任何处理");
                                                msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"在库中找到相同的激光码，此为重复数据，不做任何处理\"}";
                                                this.MQTTPublish(msg_feedback);
                                                return;
                                            }
                                        }
                                        else
                                        {
                                            log.Info("(" + strSeed + ")校验数据是否重复出错!" + result_LaserNo.strMsg);
                                            msg_feedback.text = "{\"ZC_SerialNo\":\"" + request.ZC_SerialNo + "\",\"result\":0,\"msg\":\"校验数据是否重复出错!" + result_LaserNo.strMsg + "\"}";
                                            this.MQTTPublish(msg_feedback);
                                            return;
                                        }
                                    }
                                    #endregion
                                    log.Info("(" + strSeed + ")成功解析成实体类(model.ZC_SerialNo:" + request.ZC_SerialNo + ")，将进行数据保存");
                                    model = tb_WorkPieceDataCapture_Request.ToDomainModel(request);
                                    this.doReadProduceData(strSeed, model);
                                }

                                #endregion
                            }
                        }
                        else
                        {
                            log.Error("(" + strSeed + ")无法将信息解析成实体类");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("(" + strSeed + ")数据处理出错！" + ex.ToString());
                        break;
                    }
                    break;
                case "BM21点检数据":
                    PointCheckRecord_Request PointCheck;
                    MQTT_Message msg_feedback_pointcheck = new MQTT_Message();
                    msg_feedback_pointcheck.Topic = "BM21点检数据存储结果";
                    string strSeed_pointcheck = Guid.NewGuid().ToString();
                    try
                    {
                        log.Info("(" + strSeed_pointcheck + ")接收到点检数据:" + msg.text);
                        #region 对信息的特殊处理
                        msg.text = msg.text.Replace("\\u0000", "").Replace(@"\", @"\\");
                        #endregion
                        PointCheck = JsonConvert.DeserializeObject<PointCheckRecord_Request>(msg.text);
                        if (PointCheck != null)
                        {
                            DateTime dateTime_pointcheck = DateTime.Now;
                            if (!DateTime.TryParseExact(PointCheck.CheckTime, "yyyyMMddHHmmss", new CultureInfo("en-US"), DateTimeStyles.None, out dateTime_pointcheck))
                            {
                                log.Error("(" + strSeed_pointcheck + ")解析成实体类出错,无法将CheckTime的值" + PointCheck.CheckTime + "转换成日期时间");
                                msg_feedback_pointcheck.text = "{\"ID\":\"" + PointCheck.ID + "\",\"result\":0,\"msg\":\"解析成实体类出错,无法将CheckTime的值" + PointCheck.CheckTime + "转换成日期时间\"}";
                                this.MQTTPublish(msg_feedback_pointcheck);
                                break;
                            }
                            #region 对数据进行过滤或保存
                            PointCheck.iID = null;
                            PointCheck.dDate = dateTime_pointcheck;
                            log.Info("(" + strSeed_pointcheck + ")成功解析成实体类(model.ID:" + PointCheck.ID + ")，将进行数据保存");
                            var domainModel_PointCheck = PointCheck.TransToDomainModel().Result;
                            if (domainModel_PointCheck == null)
                            {
                                log.Error("(" + strSeed_pointcheck + ")Request转换成DomainModel出错");
                                msg_feedback_pointcheck.text = "{\"ID\":\"" + PointCheck.ID + "\",\"result\":0,\"msg\":\"Request转换成DomainModel出错\"}";
                                this.MQTTPublish(msg_feedback_pointcheck);
                                return;
                            }
                            this.doReadPointCheckData(strSeed_pointcheck, domainModel_PointCheck);
                            #endregion
                        }
                        else
                        {
                            log.Error("(" + strSeed_pointcheck + ")无法将信息解析成实体类");
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error("(" + strSeed_pointcheck + ")数据处理出错！" + ex.ToString());
                        break;
                    }
                    break;
                default:
                    break;
            }
        }
        /// <summary>
        /// 发布MQTT信息
        /// </summary>
        /// <param name="msg"></param>
        private void MQTTPublish(MQTT_Message msg)
        {
            for (int i = 0; i < 10; i++)
            {
                var result_mqtt = mqtt.ClientPublish(msg);
                if (result_mqtt.bSuccess) { break; }
            }
        }

        /// <summary>
        /// 执行读点检数据
        /// </summary>
        public async void doReadPointCheckData(string strSeed, PointCheckRecord model_data)
        {
            try
            {
                if (model_data == null || 1 == 0)
                {
                    Random random = new Random();
                    // 定义两个小数
                    double minValue = 1.0;
                    double maxValue = 10000.0;
                    model_data = new PointCheckRecord()
                    {
                        //总成
                        ID = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        CheckTime = DateTime.Now.AddMinutes(-10),
                        ZC_SeriesNo = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        Result = "1",
                        EquipmentName = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                        Operator = (random.NextDouble() * (maxValue - minValue) + minValue).ToString(),
                    };
                }
                model_data.dDate = DateTime.Now;
                var dataModel = await model_data.TransToDataModel();
                lock (this.cache_PointCheckDataCapture)
                {
                    this.cache_PointCheckDataCapture.Add(dataModel);
                    log.Info("(" + strSeed + ")成功将实体类加入待存储缓存");
                }
            }
            catch (Exception ex)
            {
                log.Error("(" + strSeed + ")将实体类加入待存储缓存出错！" + ex.ToString());
            }
        }

        public void doSavePointCheckData()
        {
            while (switch_thread_SavePointCheckData)
            {
                try
                {
                    if (this.cache_PointCheckDataCapture != null && this.cache_PointCheckDataCapture.Count > 0)
                    {
                        bool dataSaved = false;
                        MQTT_Message msg = new MQTT_Message();
                        msg.Topic = "BM21点检数据存储结果";
                        var model = this.cache_PointCheckDataCapture[0];
                        var result = this.respository.saveData(model);
                        if (result.bSuccess)    //成功写入了数据库
                        {
                            log.Info("(model.ID为" + model.ID + ")的点检数据存储成功");
                            msg.text = "{\"ID\":\"" + model.ID + "\",\"result\":1,\"msg\":\"\"}";
                            dataSaved = true;
                        }
                        else
                        {
                            log.Error("(model.ID为" + model.ID + ")的点检数据存储失败！" + result.strMsg);
                            msg.text = "{\"ID\":\"" + model.ID + "\",\"result\":0,\"msg\":\"" + result.strMsg + "\"}";
                        }
                        this.MQTTPublish(msg);
                        this.cache_PointCheckDataCapture.RemoveAt(0);
                        var domainModel = model.TransToDomainModel().Result;
                        if (this.evt_FeedingNewestPointCheckData != null && dataSaved) this.evt_FeedingNewestPointCheckData(domainModel);  //向调用者反馈最新的点检数据
                    }
                    Thread.Sleep(300);
                }
                catch (Exception ex)
                {
                    log.Error("存储点检数据出现未捕获的异常！" + ex.ToString());
                }
            }
        }

        /// <summary>
        /// 处理接收到的员工数据
        /// </summary>
        private void OnEmployeeDataReceived(object? sender, EmployeeDataReceivedEventArgs e)
        {
            try
            {
                var employeeData = e.EmployeeData;
                log.Info($"WorkPieceDataCaptureHelper接收到员工数据: 工号={employeeData.EmployeeId}, 姓名={employeeData.EmployeeName}, 类别={employeeData.EmployeeType}, 接收时间={e.ReceiveTime}");

                // 保存到数据库
                if (employeeAttendanceRepository != null)
                {
                    var saveResult = employeeAttendanceRepository.SaveEmployeeAttendance(employeeData);
                    if (saveResult.bSuccess)
                    {
                        log.Info($"员工考勤数据保存成功: 工号={employeeData.EmployeeId}, 姓名={employeeData.EmployeeName}");
                    }
                    else
                    {
                        log.Error($"员工考勤数据保存失败: 工号={employeeData.EmployeeId}, 错误信息={saveResult.strMsg}");
                    }
                }
                else
                {
                    log.Warn("员工考勤数据库操作类未初始化，无法保存数据");
                }

                // 发送MQTT消息
                var msg = new MQTT_Message();
                msg.Topic = "用户登录";
                msg.text = JsonConvert.SerializeObject(employeeData);
                MQTTPublish(msg);
            }
            catch (Exception ex)
            {
                log.Error(ex, "处理员工数据时发生错误");
            }
        }
    }
}
